package pers.netty.tcp_server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception{
        System.out.println(request.toString());

//        String json = "{\"name\":\"Rain\",\"id\":4405,\"age\":28,\"createDate\":\"2018-01-25 12:17:22\",\"phone\":\"13891701101\"}";
        Response res = new Response();
        res.setName("Lyrus");
        String json = JsonCodec.objectToJson(res);
        System.out.println(json);
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                request.protocolVersion(), HttpResponseStatus.OK, Unpooled.copiedBuffer(json.getBytes(StandardCharsets.UTF_8)));
        response.headers().set("Content-Type", "text/html; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

/*        ChannelFuture future = ctx.writeAndFlush(
                LastHttpContent.EMPTY_LAST_CONTENT);

        boolean keepAlive = HttpUtil.isKeepAlive(response);
        if (keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }*/
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
